﻿#include "additemdialog.h"
#include "ui_additemdialog.h"
#include "passitem.h"
#include <QUuid>
#include <QDateTime>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include "passgensettingdialog.h"
#include <QSettings>
#include "flatui.h"
#include <QMessageBox>
#include "utils.h"
#include "globdataobj.h"

AddItemDialog::AddItemDialog(Dbtools *dbtools ,QString id,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddItemDialog)
{
    ui->setupUi(this);
    //窗口关闭时，释放内存
    this->setAttribute(Qt::WA_DeleteOnClose);

    db = dbtools;
    connect(ui->ok_pushButton,&QPushButton::clicked,[=](){
        if(checkInput()){
            QString tid =  ui->typename_comboBox->currentData().toString();
            PassItem *item;
            if(!id.isEmpty()){
                item = new PassItem(
                         id,
                         ui->account_lineEdit->text(),
                         ui->pass_lineEdit->text(),
                         tr("%1").arg(QDateTime::currentDateTime().toMSecsSinceEpoch()),
                         tr("%1").arg(QDateTime::currentDateTime().toMSecsSinceEpoch()),
                         tid,
                         ui->beizhu_textEdit->toPlainText());
            }else{
                item = new PassItem(
                         QString(""),
                              ui->account_lineEdit->text(),
                              ui->pass_lineEdit->text(),
                              tr("%1").arg(QDateTime::currentDateTime().toMSecsSinceEpoch()),
                              tr("%1").arg(QDateTime::currentDateTime().toMSecsSinceEpoch()),
                              tid,ui->beizhu_textEdit->toPlainText());
            }

            emit saveItem(item);
            close();
        }
    });

    ui->genPass_pushButton->setIcon(QIcon(":/new/prefix1/res/page_white_edit.png"));
    ui->genPass_pushButton->setToolTip(QString("点击生成密码"));
    ui->settingGen_pushButton->setIcon(QIcon(":/new/prefix1/res/cog_edit.png"));
    ui->settingGen_pushButton->setToolTip(QString("设置密码生成器"));

    initTypes();
    initDits();
    initStyle();

    if(!id.isEmpty()){
        this->setWindowTitle("修改");

        QSqlQuery query(dbtools->getDb());
        query.prepare("select * from myitems where id=:id");
        query.bindValue(":id",id);
        query.exec();
        if(query.next()){
            ui->account_lineEdit->setText(MyUtils::getDecodStr(query.value("account").toString().replace(QRegExp("\\ "),"+"),key));
            ui->beizhu_textEdit->setText(query.value("beizhu").toString());
            ui->pass_lineEdit->setText(MyUtils::getDecodStr(query.value("pass").toString().replace(QRegExp("\\ "),"+"),key));
            //选中指定的分类
            for(int x=0;x<ui->typename_comboBox->count();x++){
                if(ui->typename_comboBox->itemData(x).toString()==query.value("type_id").toString()){
                    ui->typename_comboBox->setCurrentIndex(x);
                }
            }

        }
    }else{
        this->setWindowTitle("添加");
    }
}

AddItemDialog::~AddItemDialog()
{
    delete ui;
}

void AddItemDialog::initTypes()
{
    QSqlQuery query(db->getDb());
    query.exec("select * from mytypes where del='N'");
    while (query.next()) {
        ui->typename_comboBox->addItem(query.value("type_name").toString(),query.value("id"));
    }

}

void AddItemDialog::initDits()
{
    allDit.clear();
    xxzmDit.clear();
    dxzmDit.clear();
    numDit.clear();
    tsfhDit.clear();

    xxzmDit<<QStringLiteral("a")<<QStringLiteral("b")<<QStringLiteral("c")<<QStringLiteral("d")
          <<QStringLiteral("e")<<QStringLiteral("f")<<QStringLiteral("g")<<QStringLiteral("h")
         <<QStringLiteral("i")<<QStringLiteral("j")<<QStringLiteral("k")<<QStringLiteral("l")
        <<QStringLiteral("m")<<QStringLiteral("n")<<QStringLiteral("o")<<QStringLiteral("p")
       <<QStringLiteral("q")<<QStringLiteral("r")<<QStringLiteral("s")<<QStringLiteral("t")
      <<QStringLiteral("u")<<QStringLiteral("v")<<QStringLiteral("w")<<QStringLiteral("x")
     <<QStringLiteral("y")<<QStringLiteral("z");
    dxzmDit <<QStringLiteral("A")<<QStringLiteral("B")<<QStringLiteral("C")<<QStringLiteral("D")
           <<QStringLiteral("E")<<QStringLiteral("F")<<QStringLiteral("G")<<QStringLiteral("H")
          <<QStringLiteral("I")<<QStringLiteral("J")<<QStringLiteral("K")<<QStringLiteral("L")
         <<QStringLiteral("M")<<QStringLiteral("N")<<QStringLiteral("O")<<QStringLiteral("P")
        <<QStringLiteral("Q")<<QStringLiteral("R")<<QStringLiteral("S")<<QStringLiteral("T")
       <<QStringLiteral("U")<<QStringLiteral("V")<<QStringLiteral("W")<<QStringLiteral("X")
      <<QStringLiteral("Y")<<QStringLiteral("Z");
    numDit <<QStringLiteral("1")<<QStringLiteral("2")<<QStringLiteral("3")<<QStringLiteral("4")
          <<QStringLiteral("5")<<QStringLiteral("6")<<QStringLiteral("7")<<QStringLiteral("8")
         <<QStringLiteral("9");
    tsfhDit<<QStringLiteral(".")<<QStringLiteral("-")<<QStringLiteral("_")
          <<QStringLiteral("=")<<QStringLiteral("+")<<QStringLiteral("*")
         <<QStringLiteral("&")<<QStringLiteral("%")<<QStringLiteral("$")
        <<QStringLiteral("#")<<QStringLiteral("@")<<QStringLiteral("!")
       <<QStringLiteral("[")<<QStringLiteral("]")<<QStringLiteral("{")
      <<QStringLiteral("}")<<QStringLiteral("'")<<QStringLiteral(":")<<QStringLiteral(";")
     <<QStringLiteral("?")<<QStringLiteral("/");

    QSettings settings;
    int xxzm = settings.value("passgen/xxzm").isValid()?settings.value("passgen/xxzm").toInt():1;
    int dxzm = settings.value("passgen/dxzm").isValid()?settings.value("passgen/dxzm").toInt():1;
    int num = settings.value("passgen/num").isValid()?settings.value("passgen/num").toInt():1;
    int tsfh = settings.value("passgen/tsfh").isValid()?settings.value("passgen/tsfh").toInt():1;
    for(int x=0;x<xxzm;x++){
        foreach (QString s, xxzmDit) {
            allDit.append(s);
        }
    }
    for(int x=0;x<dxzm;x++){
        foreach (QString s, dxzmDit) {
            allDit.append(s);
        }
    }
    for(int x=0;x<num;x++){
        foreach (QString s, numDit) {
            allDit.append(s);
        }
    }
    for(int x=0;x<tsfh;x++){
        foreach (QString s, tsfhDit) {
            allDit.append(s);
        }
    }

}

void AddItemDialog::initStyle()
{
    FlatUI::Instance()->setLineEditQss(ui->account_lineEdit);
    FlatUI::Instance()->setLineEditQss(ui->pass_lineEdit);
    FlatUI::Instance()->setPushButtonQss(ui->genPass_pushButton,5, 8, "#3498DB",
                                         "#FFFFFF", "#5DACE4", "#E5FEFF", "#2483C7", "#A0DAFB");
    FlatUI::Instance()->setPushButtonQss(ui->settingGen_pushButton);
    FlatUI::Instance()->setPushButtonQss(ui->cancel_pushButton);
    FlatUI::Instance()->setPushButtonQss(ui->ok_pushButton,5, 8, "#1ABC9C",
                                         "#E6F8F5", "#2EE1C1", "#FFFFFF", "#16A086", "#A7EEE6");

}

bool AddItemDialog::checkInput()
{
    bool ischeck = false;
    //账号不能为空
    if(ui->account_lineEdit->text().isEmpty()){
        QMessageBox::warning(this,tr("警告"),tr("账号不能为空!"),QMessageBox::Ok);
    }else if(ui->pass_lineEdit->text().isEmpty()){
        QMessageBox::warning(this,tr("警告"),tr("密码不能为空!"),QMessageBox::Ok);
    }else{
        ischeck = true;
    }

    return ischeck;
}

void AddItemDialog::on_genPass_pushButton_clicked()
{
    //读取密码生成设置信息
    QSettings settings;

    int length = settings.value("passgen/passlen").isValid()?settings.value("passgen/passlen").toInt():1;

    QTime time;
    time = QTime::currentTime();
    qsrand(time.msec()+time.second()*1000);
    QString s;
    for(int a=0;a<length;a++){
        s.append(allDit.at( 0+qrand()%allDit.count()));

    }
    ui->pass_lineEdit->setText(s);
}

void AddItemDialog::on_settingGen_pushButton_clicked()
{
    PassGenSettingDialog *dlg = new PassGenSettingDialog(this);
    dlg->exec();
}

void AddItemDialog::on_cancel_pushButton_clicked()
{
    close();
}
